import { AudioClip, AudioSource, Component, Node, _decorator, director, game, isValid } from "cc";
import { LoadCtrl } from "./LoadCtrl";


const { ccclass, property } = _decorator;
@ccclass('SoundCtrl')
export default class SoundCtrl extends Component {

    private static audioSource: AudioSource = null;
    protected onLoad(): void {
        director.addPersistRootNode(this.node);
        SoundCtrl.audioSource = this.getComponent(AudioSource) || this.addComponent(AudioSource);
    }
    static stopMusicSound() {
        this.audioSource.stop();
    }

    static playMusic(name: string, loop = true) {
        LoadCtrl.loadBundleRes("sounds/music/" + name, AudioClip, (clip) => {
            this.audioSource.clip = clip;
            this.audioSource.loop = loop;
            this.audioSource.play();
        })
    }

    private static effectList: Map<string, number> = new Map();
    static playEffect(name: string, coolTime = 0) {
        LoadCtrl.loadBundleRes("sounds/effect/" + name, AudioClip, (clip) => {
            if (coolTime <= 0) {
                this.audioSource.playOneShot(clip);
                return;
            }
            if (this.effectList.has(name)) {//已有一个同名clip在播放
                return;
            }
            this.effectList.set(name, coolTime);
            this.audioSource.playOneShot(clip);
        })
    }

    static effectPlayTick(dt) {
        if (this.effectList.size > 0) {
            let values = Array.from(this.effectList.values());
            let keys = Array.from(this.effectList.keys());
            for (let i = values.length - 1; i >= 0; i--) {
                values[i] -= dt;
                if (values[i] <= 0) {
                    this.effectList.delete(keys[i]);
                }
                else {
                    this.effectList.set(keys[i], values[i]);
                }
            }
        }
    }

    // static playMusic(target: Node, name: string, loop = true) {
    //     if (target) {
    //         let source = target.getComponent(AudioSource) || target.addComponent(AudioSource);

    //         SoundManager.Instance.playAudio(source, name, true);

    //         source.loop = loop;
    //     }
    // }

    // static playEffectByNewSource(target: Node, name: string) {

    //     if (target) {
    //         let source = target.getComponent(AudioSource) || target.addComponent(AudioSource);

    //         SoundManager.Instance.playAudio(source, name);
    //     }
    //     else {
    //         let node = new Node();
    //         let source = node.addComponent(AudioSource);
    //         SoundManager.Instance.playAudio(source, name);

    //         source.scheduleOnce(() => {
    //             node.destroy();
    //         }, 3);
    //     }
    // }

}